package com.minaClient.service;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IoSession;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.minaClient.fileHandler.ClientSend;
import com.minaClient.utils.Comunication;
import com.minaClient.utils.Consant;
import com.minaClient.utils.FileInfo;
import com.minaClient.utils.Msg;

public class Iohandler extends IoHandlerAdapter{
    private Comunication com=new Comunication();
	    private List<Object> list=new ArrayList<>();
	    private Msg msg=new Msg();
	    FileInfo fi=new FileInfo();
		File file=new File("H:/迅雷下载/圆梦巨人.720p.国英双语.BD中英双字[www.66ys.tv].mkv");

	Logger log=Logger.getLogger(Iohandler.class.getName());
	 ClientSend client;
	@Override
    public void sessionOpened(IoSession session) throws Exception {
        super.sessionOpened(session);
		
    }
    @Override
    public void messageReceived(IoSession session, Object message) throws Exception {
    	   JSONObject json = JSON.parseObject(message.toString());
    	   Msg msgjson = JSON.parseObject(json.getString("msg"), Msg.class) ;
			  int code =msgjson.getCode();
			  String msgC = msgjson.getMsg();
			  
			 
    	  
			if(code==Consant.CODE_BITHEART){
	    		log.debug( "接收到服务器端心跳消息：");
//	    		 upLoadComand();
	    	}else if(code==Consant.CODE_START) {
	    		    log.debug( "接收到服务器上传指令："+msgC);
	    		    client = new ClientSend();  
	    			client.connect(file.getAbsolutePath());
	    		    
	    	}else if(code==Consant.CODE_STOP) {
    		    log.debug( "文件上传成功：关闭服务器");
    		   
    		    client.closed();
    	   }
    }

    
    public void upLoadComand() {
    	list.clear();
		log.debug( "客户端发送上传文件命令：");
		//发送文件上传命令
		String [] namearr=file.getName().split("\\.");
		fi.setName(namearr[0]);
		fi.setFileType(namearr[1]);
		fi.setDestPath(file.getParentFile()+"/data");
		fi.setCreate_time(file.lastModified()+"");
		fi.setModify_time(file.lastModified()+"");
		fi.setVisit_time(file.lastModified()+"");
	    fi.setSuffix(file.getName().substring(file.getName().length()-4));
		
		
		msg.setCode(Consant.CODE_FILE_UPLOAD);
		msg.setMsg(Consant.MSG_FILE_UPLOAD);
		list.add(fi);
		 com.setMsg(msg);
		 com.setList(list);
		SessionManager.getInstance().writeToServer(JSON.toJSON(com));
		log.debug( "客户端发送上传文件命令结束：");
    }
	@Override
	public void sessionClosed(IoSession session) throws Exception {
		// TODO Auto-generated method stub
		super.sessionClosed(session);
		log.debug( "服务器关闭："+session.toString());
		SessionManager.getInstance().removeSession();
		MinaService.exitHeartBit=false;
		log.debug( "停止发送心跳：");
		
		log.debug( "重新连接：");
		MinaService.mMinaService.minaClientStart();
	}
    
    
}
